<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>

    </style>
</head>
<body>
    正在测试ajax的二合一封装
    <input type="button" id="btn1" value="get请求">
    <input type="button" id="btn2" value="post请求">
    <div id="box"></div>
</body>
<script>
    const obtn1 = document.getElementById("btn1")
    const obtn2 = document.getElementById("btn2")

    obtn1.onclick = function(){
        ajax({
            url:"http://localhost:3000/api",
            success:res=>{
                console.log(res);
            },
            // data:{aaa:10,bbb:20}
        })
    }

    obtn2.onclick = function(){
        ajax({
            type:"post",         
            url:"http://localhost:3000/api",             
            success:res=>{
                console.log(res)
            },     
            error:code => {
                console.log(code)
            },       
            data:{
                a:10,b:20,c:30,d:40
            }             
        })
    }
    function ajax(ops){
        ops=ops||{};
        let{data={},type="get",url,success,error}=ops;
        let str="";
        for(let i in data){
            str+=`${i}=${data[i]}&`;
        }if(type==="get"){
            url+="?"+str.slice(0,str.length-1);
        }
        const xhr=new XMLHttpRequest();
        xhr.open(type,url,true);
        xhr.onload=function(){  //onload说明ajax的状态已经到达了4,（完成）响应内容解析完成，可以在客户端调用了
            if(xhr.status===200){   //http的状态码为200表示交易成功
                success(xhr.responseText);
            }else{
                error&&error(xhr.status);
            }
        }
        if(type==="get"){
            xhr.send();
        }else{
            xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            xhr.send(str);
        }
    }
</script>
</html>